// Fill out your copyright notice in the Description page of Project Settings.


#include "SessionSetting.h"

#include "MultiplayerSessionsSubsystem.h"
#include "Components/Button.h"
#include "Components/EditableText.h"
#include "ThirdParty/Steamworks/Steamv157/sdk/public/steam/steam_api.h"

bool USessionSetting::Initialize()
{
	if (!Super::Initialize())
	{
		return false;
	}

	if (CreateButton)
	{
		CreateButton->OnClicked.AddDynamic(this, &ThisClass::CreateButtonClicked);
	}

	if (CancelButton)
	{
		CancelButton->OnClicked.AddDynamic(this, &ThisClass::CancelButtonClicked);
	}

	if (EditableText)
	{
		EditableText->SetText(FText::FromString(GetPlayerSteamName().Append("'s Game")));
	}

	UGameInstance* GameInstance = GetGameInstance();
	if (GameInstance)
	{
		MultiplayerSessionsSubsystem = GameInstance->GetSubsystem<UMultiplayerSessionsSubsystem>();
	}
	

	return true;
}

void USessionSetting::CreateButtonClicked()
{
	CreateButton->SetIsEnabled(false);
	if (MultiplayerSessionsSubsystem)
	{
		MultiplayerSessionsSubsystem->CreateSession(4,EditableText->GetText().ToString());
	}
	
	RemoveFromParent();
}

void USessionSetting::CancelButtonClicked()
{
	RemoveFromParent();
}

FString USessionSetting::GetPlayerSteamName()
{
	FString ret{};

	if (SteamAPI_Init())
	{
		ret = FString(SteamFriends()->GetPersonaName());
	}

	return ret;
}
